"""
multiprocessing多进程编程

核心知识：
    1.多进程编码首选：concurrent.futures.ProcessPoolExecutor
"""

import os
import time
import multiprocessing


def use_fork():
    # fork只能用于Linux/Unix
    pid = os.fork()
    print("Kevin")
    if pid == 0:
        print("子进程 {}, 父进程是: {}".format(os.getpid(), os.getppid()))
    else:
        print("父进程: {}".format(pid))

    time.sleep(2)

    # 输出结果：
    """
    Kevin
    父进程: 1223
    Kevin
    子进程 1223, 父进程是: 1221
    """


def get_html(n):
    time.sleep(n)
    return n


def use_process():
    process = multiprocessing.Process(target=get_html, args=(2,))
    process.start()
    print("pid: ", process.pid)
    process.join()
    print("主进程已运行完毕")
    # 输出结果：
    """
    pid:  1341
    主进程已运行完毕
    """


def use_process_pool():
    """
    使用线程池
    """

    pool = multiprocessing.Pool(multiprocessing.cpu_count())
    # # 异步提交
    # result = pool.apply_async(get_html, args=(2,))
    # # 关闭进程池
    # pool.close()
    # # 阻塞
    # pool.join()
    # print(result.get())
    # 输出结果：
    """
    2
    """

    # imap方法
    # for result in pool.imap(get_html, [1, 8, 6]):
    #     print(result)
    # # 输出结果：
    # """
    # 1
    # 8
    # 6
    # """

    for result in pool.imap_unordered(get_html, [1, 8, 6]):
        print(result)
    # 输出结果：
    """
    1
    6
    8
    """


if __name__ == '__main__':
    # use_fork()
    # use_process()
    use_process_pool()
